import React, {Component} from 'react'
import { connect } from 'react-redux'
import {Spin, Tabs, message, Avatar, Icon, Modal} from 'antd'
import {http, sleep, renderTitle, fromNow, notLogin, post, dropRepeat, filterText} from '../../common/js/utils'
import {Header} from '../../layout/header'
import DPlayer from 'dplayer'
import {Link} from 'react-router-dom'
import moment from 'moment'
import 'moment/locale/zh-cn'
import 'dplayer/dist/DPlayer.min.css'
import './style.scss'
import {ReplyForm} from './reply_form'
import {NewComment} from './comment_form'
import {UserCard} from '../../component/user_card'

moment.locale('zh-cn')

function callback(key) {
  // key
}

function mapStateToProps(state, props) {
  return {
    userInfo: state.get('userInfo')
  }
}

@connect(mapStateToProps)
class Detail extends Component {

  state = {
    loading: false,
    detail: {},
    relativeMovies: [],
    commentLoading: false,
    comments: []
  }

  page = 0
  size = 10
  totalComments = 0

  replySuccess = (item, comment) => {
    comment.replies.unshift(item)
    comment.reply_count++
    const {comments} = this.state
    this.setState({comments})
  }

  commentSuccess = (item) => {
    const {comments} = this.state
    comments.unshift(item)
    this.setState({comments})
  }

  async getDetail() {
    const props = this.props
    this.setState({
      loading: true
    })
    let res = await http({
      method: 'get',
      url: `/api/movies/detail/${props.match.params.id}`
    })
    this.setState({
      detail: res.data.movie,
      relativeMovies: res.data.relatives,
      loading: false
    })
    renderTitle(res.data.movie.title)
    this.play(res.data.movie)
  }

  getComments = async () => {
    const props = this.props
    if (this.page === 0) {
      this.setState({comments: []})
    }
    if (this.state.commentLoading) return
    let comments = await http({
      method: 'get',
      url: `/api/comments/list?_id=${props.match.params.id}&page=${this.page}&size=${this.size}`
    }, commentLoading => {
      this.setState({commentLoading})
    })
    this.totalComments = comments.total
    const d = this.state.comments.concat(comments.data)
    this.setState({
      comments: dropRepeat(item => item._id)(d)
    })
  }

  onRemove = (item, key) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除？',
      onOk: () => {
        post('/api/comments/remove', {
          commentId: item._id
        }).then(res => {
          if (res.result === 1) {
            message.success('删除成功')
            const comments = this.state.comments
            comments.splice(key, 1)
            this.setState({comments})
          }
        })
      }
    })
  }

  loadMore = () => {
    if (this.totalComments > (this.page + 1) * this.size) {
      this.page++
      this.getComments()
    }
  }

  moreReplies = (item, key, page) => {
    page = item.repliesPage || (item.repliesPage = 0)
    const comments = this.state.comments
    http({
      method: 'get',
      url: `/api/reply/list?commentId=${item._id}&page=${page}&size=5`
    }).then(res => {
      if (item.repliesPage === 0) item.replies = []
      item.replies = item.replies.concat(res.data)
      item.replies = dropRepeat(a => a._id)(item.replies)
      item.reply_count = res.total
      item.repliesPage = res.page
      comments.splice(key, 1, item)
      this.setState({comments})
    })
  }

  delReply = (it, k, item, key) => {
    Modal.confirm({
      title: '提示',
      content: '确定删除？',
      onOk: () => {
        post('/api/reply/del', {
          replyId: it._id
        }).then(res => {
          if (res.result === 1) {
            const comments = this.state.comments
            comments[key].reply_count--
            comments[key].replies.splice(k, 1)
            this.setState({comments})
          }
        })
      }
    })
  }

  goodReply = (it, k, item, key) => {
    post('/api/reply/good', {
      replyId: it._id
    }).then(res => {
      if (res.result === 1) {
        const comments = this.state.comments
        comments[key].replies[k].clicked = !comments[key].replies[k].clicked
        if (comments[key].replies[k].clicked) {
          comments[key].replies[k].good_count++
        } else {
          comments[key].replies[k].good_count--
        }
        this.setState({comments})
      }
    })
  }

  async play(item) {
    await sleep(1000)
    const dom = document.getElementById('videoPlayer')
    if (!dom) return
    this.player = new DPlayer({
      container: dom,
      screenshot: true,
      autoplay: true,
      video: {
        url: item.video,
        pic: item.cover,
        thumbnails: item.cover
      }
    })
  }

  like = (item, key) => {
    const {userInfo} = this.props
    if (userInfo.get('status') !== 1) {
      notLogin()
      return
    }
    if (this.goodLoading) return
    post('/api/comments/good', {
      commentId: item._id
    }, loading => this.goodLoading = loading).then(res => {
      if (res.result === 1) {
        let comments = this.state.comments
        comments[key].clicked = !comments[key].clicked
        if (comments[key].clicked) {
          comments[key].good_count++
        } else {
          comments[key].good_count--
        }
        this.setState({comments})
      }
    })
  }

  componentDidUpdate(preProps, preState, snapshot) {
    if (preProps.match.params.id !== this.props.match.params.id) {
      this.page = 0
      this.getDetail()
      this.getComments()
    }
  }

  componentWillMount() {
    this.getDetail()
    this.getComments()
  }

  render() {
    if (this.state.loading) return (
      <Spin size="large" wrapperClassName="full">
        <div className="full" />
      </Spin>
    )
    const { detail, relativeMovies, comments } = this.state
    const {userInfo} = this.props
    const more = this.totalComments > (this.page + 1) * this.size
    return (
      <div className="movie-detail-container">
        <Header />
        <div className="movie-detail">
          <div className="left">
            <div className="video-wrapper">
              <div id="videoPlayer" />
            </div>
            <NewComment _id={this.props.match.params.id} onSubmit={this.commentSuccess} />
            <div className="left-comment">
              <h3>热门评论</h3>
              {
                <div className="comments-list">
                  {
                    comments.length
                      ? comments.map((item, key) => (
                        <div className="comment-item" key={key}>
                          <div className="comment-main">
                            <div className="comment-top">
                              <UserCard
                                _id={item.createdBy._id}
                                placement="right"
                              >
                                <Avatar title={item.createdBy.nickname} size={40} src={item.createdBy.face} />
                              </UserCard>
                              <span className="nick-date">
                                <span title={item.createdBy.nickname} className="comment-nickname">{item.createdBy.nickname}</span>
                                <span className="comment-time">{fromNow(item.meta.createdAt)}</span>
                              </span>
                            </div>
                            <div className="comment-con-box">
                              <div className="comment-content" dangerouslySetInnerHTML={{__html: filterText(item.content)}} />
                            </div>
                            <div className="comment-right">
                              <span className={item.clicked ? 'comment-like clicked' : 'comment-like'}>
                                <Icon type="like"
                                      theme={item.clicked ? 'filled' : 'outlined'}
                                      title={item.clicked ? '取消赞' : '赞'}
                                      onClick={e => this.like(item, key)}
                                      style={{
                                        cursor: 'pointer'
                                      }}
                                />
                                <span title={`${item.good_count}人觉得很赞`} style={{
                                  fontSize: 12,
                                  margin: '0 0 0 3px'
                                }}>{item.good_count}</span>
                              </span>
                              {
                                userInfo.get('_id') === item.createdBy._id
                                  ? <span onClick={e => this.onRemove(item, key)} title="删除" className="edit del">删除</span>
                                  : <ReplyForm
                                      comment={item}
                                      onSuccess={e => this.replySuccess(e, item)}
                                    >
                                      <span title={`回复“${item.createdBy.nickname}”`} className="edit" >回复</span>
                                    </ReplyForm>
                              }
                            </div>
                          </div>
                          {
                            <div className="reply-list">
                              {
                                item.replies && item.replies.map((it, k) => (
                                  <div className="reply-item" key={it._id}>
                                    <div className="reply-top">
                                      <UserCard
                                        _id={it.createdBy._id}
                                        placement="right"
                                      >
                                        <Avatar title={it.createdBy.nickname} size={40} src={it.createdBy.face} />
                                      </UserCard>
                                      <span className="nick-date">
                                        <span title={it.createdBy.nickname} className="comment-nickname">{it.createdBy.nickname}</span>
                                        <span className="comment-time">{fromNow(it.meta.createdAt)}</span>
                                      </span>
                                    </div>
                                    <div className="comment-con-box">
                                      {
                                        it.at ?
                                          <span className="reply-to" title={it.replyTo.nickname}>
                                            回复&nbsp;@<span style={{color: '#d9d9d9'}}>{it.replyTo.nickname}</span>：
                                            <span style={{color: '#d9d9d9'}} dangerouslySetInnerHTML={{__html: filterText(it.at.content)}} />
                                          </span> :
                                          null
                                      }
                                      <div className="comment-content" dangerouslySetInnerHTML={{__html: filterText(it.content)}} />
                                    </div>
                                    <div className="comment-right">
                                      <span className={it.clicked ? 'comment-like clicked' : 'comment-like'}>
                                        <Icon type="like"
                                              theme={it.clicked ? 'filled' : 'outlined'}
                                              title={it.clicked ? '取消赞' : '赞'}
                                              onClick={e => this.goodReply(it, k, item, key)}
                                              style={{
                                                cursor: 'pointer'
                                              }}
                                        />
                                        <span title={`${it.good_count}人觉得很赞`} style={{
                                          fontSize: 12,
                                          margin: '0 0 0 3px'
                                        }}>{it.good_count}</span>
                                      </span>
                                      {
                                        userInfo.get('_id') === it.createdBy._id
                                          ? <span onClick={e => this.delReply(it, k, item, key)} title="删除" className="edit del">删除</span>
                                          : <ReplyForm
                                              reply={it}
                                              comment={item}
                                              onSuccess={e => this.replySuccess(e, item)}
                                            >
                                                <span title={`回复“${it.createdBy.nickname}”`} className="edit">回复</span>
                                            </ReplyForm>
                                      }
                                    </div>
                                  </div>
                                ))
                              }
                              {
                                item.replies.length >= item.reply_count
                                  ? null
                                  : <div title="更多回复" className="more-load" onClick={e => {
                                      item.repliesPage++
                                      this.moreReplies(item, key)}
                                    }>更多回复</div>
                              }
                            </div>
                          }
                        </div>
                      ))
                      : <div style={{
                        padding: '20px 0',
                        textAlign: 'center',
                        color: '#fff'
                      }}>还没有人评论呦~</div>
                  }
                </div>
              }
              {
                this.state.commentLoading
                  ? <Spin style={{
                    width: '100%'
                  }} size="small" />
                  : comments.length
                  ? more
                    ? <div className="more-load" onClick={this.loadMore}>查看更多评论</div>
                    : <div className="no-more">没有更多了</div>
                  : null
              }
            </div>
          </div>
          <div className="video-sidebar">
            <Link className='homeLink' to={'/'}>回到首页</Link>
            <Tabs defaultActiveKey="1" onChange={callback}>
              <Tabs.TabPane tab="关于本片" key="1">
                <h1>{detail.title}</h1>
                <dl className="det" >
                  <dt><span className="label">豆瓣评分：</span><span className="badge" style={{ backgroundColor: '#52c41a' }}>{detail.rate}</span> 分</dt>
                  <dt><span className="label">电影分类：</span>{detail.movieTypes && detail.movieTypes.map((item, key) => (
                    <span key={key} >{item}&nbsp;&nbsp;</span>
                  ))}</dt>
                  <dt><span className="label">主演：</span>{detail.casts && detail.casts.map((item, key) => (
                    <span className="cast" key={key}>{item}&nbsp;&nbsp;</span>
                  ))}</dt>
                  <dt><span className="label">导演：</span>{detail.directors && detail.directors.map((item, key) => (
                    <span className="cast" key={key}>{item}&nbsp;&nbsp;</span>
                  ))}</dt>
                  <dt><span className="label">地区：</span>{detail.countries && detail.countries.map((item, key) => (
                    <span key={key}>{item}&nbsp;&nbsp;</span>
                  ))}</dt>
                  <dt><span className="label">上映时间：</span><span>{moment(detail.pubdate).format('YYYY-MM')}</span></dt>
                  <dt><span className="label">更新时间：</span>{moment(detail.meta.updatedAt).fromNow()}</dt>
                  <dt><span className="label">影片介绍：</span>{detail.summary}</dt>
                </dl>
              </Tabs.TabPane>
              <Tabs.TabPane tab="同类电影" key="2">
                {
                  relativeMovies.map(item => (
                    <div key={item._id} className="media" >
                      <Link to={`/detail/${item._id}`} className="img-b">
                        <img width="90" src={item.poster} alt={item.title} title={item.title} />
                      </Link>
                      <div className="media-body">
                        <h6 className="media-title" title={`${item.title}（${moment(detail.pubdate).format('YYYY-MM')}）`}>
                          <Link to={`/detail/${item._id}`}>{`${item.title}（${moment(detail.pubdate).format('YYYY-MM')}）`}</Link>
                        </h6>
                        <ul className="list-unstyled">
                          <li>{
                            item.countries && item.countries.map((item, key) => (
                              <span key={key}>{item}&nbsp;&nbsp;</span>
                            ))
                          }</li>
                          <li><span className="label">主演：</span>{
                            item.casts && item.casts.map((item, key) => (
                              <span className="cast" key={key}>{item}&nbsp;&nbsp;</span>
                            ))
                          }</li>
                        </ul>
                      </div>
                    </div>
                  ))
                }
              </Tabs.TabPane>
            </Tabs>
          </div>
        </div>
      </div>
    )
  }
}

export default Detail